package com.ruoyi.backend2.aspect;

import com.ruoyi.backend2.domain.User;
import com.ruoyi.backend2.interfaces.Role;
import com.ruoyi.backend2.utils.GlobalThreadLocalUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class RoleCheckerAspect {
    @Autowired
    private RedisTemplate redisTemplate;

    @Before("@annotation(role)")
    public void checkRole(JoinPoint joinPoint, Role role) {
        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取方法
        Method method = signature.getMethod();
        // 获取方法上的Role注解
        Role annotation = AnnotationUtils.findAnnotation(method, Role.class);
        if (annotation == null) {
            throw new RuntimeException("在方法上找不到角色注释.");
        }
        // 获取当前用户的角色
        int currentUserRole = getCurrentUserRole(annotation);
        // 检查用户角色是否符合要求
        if (currentUserRole < annotation.value()) {
            throw new SecurityException("拒绝访问！用户没有所需的权限: " + annotation.value());
        }
    }

    private int getCurrentUserRole(Role role) {
        Integer id = GlobalThreadLocalUtil.get("id");
        Object object = redisTemplate.opsForValue().get("user:" + id);
        if (object == null) {
            return 0;
        }
        return ((User) object).getRole();
    }

}
